﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
using System.Windows.Controls.Primitives;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;

namespace InstantWatch.Controls {
	class ScrollListBox : ListBox {

		public ScrollListBox()
			: base() {
		}

		protected override void OnSelectionChanged(SelectionChangedEventArgs e) {
			base.OnSelectionChanged(e);
			//	RefreshSelection();
		}

		public void RefreshSelection() {
			ItemContainerGenerator generator = this.ItemContainerGenerator;
			if (generator.Status != GeneratorStatus.ContainersGenerated)
				return;
			Storyboard animationTimeLine = new Storyboard();

			for (int i = 0; i < this.Items.Count; ++i) {
				ListBoxItem item = generator.ContainerFromIndex(i) as ListBoxItem;
				if (VisualTreeHelper.GetChildrenCount(item) == 0)
					continue;

				this.AnimateItem(item, i, animationTimeLine);
			}

			animationTimeLine.Begin(this);
		}

		private const double ItemDefaultWidth = 200;
		private const double ItemDefaultOpacity = 1;
		private const double ItemSelectedWidth = 220;
		//private double ItemNotVisibleWidth = .01;
		//private double ItemNotVisibleOpacity = 0;
		private static Duration AnimationDuration { get { return new Duration(TimeSpan.FromMilliseconds(250)); } }
		private DoubleAnimation ItemSelectedAnimation = new DoubleAnimation() { To = ItemSelectedWidth, Duration = AnimationDuration };
		private DoubleAnimation ItemVisibleAnimation = new DoubleAnimation() { To = ItemDefaultWidth, Duration = AnimationDuration };
		private DoubleAnimation ItemInvisibleAnimation = new DoubleAnimation() { To = .01, Duration = AnimationDuration };

		private void AnimateItem(ListBoxItem item, int i, Storyboard theBoard) {
			
			double width = 200;
			double opacity = 1;

			DoubleAnimation animation = null;

			if (double.IsNaN(item.Width))
				animation = ItemVisibleAnimation;			
			if (i == SelectedIndex) {
				animation = ItemSelectedAnimation;
			} else if (i < SelectedIndex) {
				animation = ItemInvisibleAnimation;
			}

			if (item.Width == width) return;

			//-- Set the Properties
			Storyboard.SetTarget(item, animation);
			Storyboard.SetTargetProperty(animation, new PropertyPath(ListBoxItem.WidthProperty));
			
			//item.BeginAnimation(ListBoxItem.WidthProperty, new DoubleAnimation() { To = width, Duration = AnimationDuration });
			//item.BeginAnimation(ListBoxItem.OpacityProperty, new DoubleAnimation() { To = opacity, Duration = AnimationDuration });
		}
	}
}
